package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
	jaTranslations "github.com/go-playground/validator/v10/translations/ja"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
	"net/http"
	"saleforce/sf-backend-gateway/i18n"
	"saleforce/sf-backend-gateway/validate"
	ser "saleforce/sf-backend-user/service"
	pr "saleforce/sf-common/params/backend-user"
	proto "saleforce/sf-common/protoc/backend-user"
	resp "saleforce/sf-common/response"
	"saleforce/sf-common/utils"
	"strconv"
)

type BkMenuController struct {
}

func (u BkMenuController) Detail(c *gin.Context) {
	id := c.DefaultQuery("id", "")
	if id == "" {
		c.JSON(http.StatusOK, resp.Resp{}.Warning(501, i18n.T("ID is null", c.GetHeader("lang"))))
		return
	}
	i, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, resp.Resp{}.Warning(501, i18n.T("ID format error, Id is a integer", c.GetHeader("lang"))))
		return
	}
	param := proto.IntIdParam{
		Id: i,
	}
	menu, err := ser.MenuService{}.GetMenu(c, &param)
	if err != nil {
		c.JSON(http.StatusOK, resp.Resp{}.Warning(501, i18n.T(err.Error(), c.GetHeader("lang"))))
		return
	}
	var res any = menu
	c.JSON(http.StatusOK, resp.Resp{}.Success(&res))
	return
}

func (u BkMenuController) MenuList(c *gin.Context) {
	var param pr.MenuListParam
	lang := c.GetHeader("lang")
	trans, _ := validate.Uni.GetTranslator(lang)
	switch lang {
	case "cn":
		_ = zhTranslations.RegisterDefaultTranslations(validate.Validate, trans)
	case "jp":
		_ = jaTranslations.RegisterDefaultTranslations(validate.Validate, trans)
	case "en":
		_ = enTranslations.RegisterDefaultTranslations(validate.Validate, trans)
	default:
		_ = zhTranslations.RegisterDefaultTranslations(validate.Validate, trans)
	}
	if err := c.ShouldBind(&param); err != nil {
		if errs, ok := err.(validator.ValidationErrors); ok {
			c.JSON(http.StatusOK, resp.Resp{}.Warning(501, errs[0].Translate(trans)))
			return
		}
		c.JSON(http.StatusOK, resp.Resp{}.Warning(502, i18n.T(err.Error(), lang)))
		return
	}
	pageInt := param.Page
	pageInt64 := int64(pageInt)
	sizeInt := param.Size
	sizeInt64 := int64(sizeInt)
	p := proto.MenuListParam{
		Keyword:  utils.WrapString(param.Keyword),
		MenuType: utils.WrapInt32(param.MenuType),
		Page:     utils.WrapInt64(&pageInt64),
		Size:     utils.WrapInt64(&sizeInt64),
		Status:   utils.WrapInt32(param.Status),
	}
	lst, err := ser.MenuService{}.GetMenuList(c, &p)
	if err != nil {
		c.JSON(http.StatusOK, resp.Resp{}.Warning(500, i18n.T(err.Error(), lang)))
		return
	}
	menus, page, total, size := lst.GetMenus(), lst.GetPage(), lst.GetTotal(), lst.GetSize()
	res := resp.Pagination[*proto.Menu]{}.Init(menus, int(page), int(size), total)
	var resAny any = res
	c.JSON(http.StatusOK, resp.Resp{}.Success(&resAny))
}
